package com.aoxin.util;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.aoxin.model.course.SlfChildren;
import com.aoxin.model.opm.SlfEmployee;
import com.aoxin.model.opm.SlfUser;
import com.aoxin.service.inter.course.webCourse.ChildrenService;

/**
 * 线程局部变量工具类
 * 
 * @author Melody
 *
 */
public class ThreadLocalUtil {

	private static ThreadLocal<HttpServletRequest> request = new ThreadLocal<HttpServletRequest>();

	private static ThreadLocal<HttpServletResponse> response = new ThreadLocal<HttpServletResponse>();

	public static HttpServletRequest getRequest() {
		setRequest();
		return request.get();
	}

	private static void setRequest() {
		HttpServletRequest req = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
		request.set(req);
	}

	public static HttpServletResponse getResponse() {
		setResponse();
		return response.get();
	}

	public static void setResponse() {
		HttpServletResponse req = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes())
				.getResponse();
		response.set(req);
	}

	public static SlfEmployee getEmployee() {
		setRequest();
		SlfEmployee employee = null;
		String token = request.get().getParameter("token");
		if (null == token) {
			String employeeSession = (String) request.get().getSession().getAttribute("employeeSession");
			if (null == employeeSession) {
				throw new IllegalArgumentException(ErrorUtil.LOGIN_EXPIRE);
			}
			token = (String) RedisUtil.get(employeeSession);
		}
		employee = (SlfEmployee) RedisUtil.get(token);
		return employee;
	}

	public static SlfUser getUser() {
		setRequest();
		SlfUser slfUser = (SlfUser) request.get().getSession().getAttribute("userSession");
		return slfUser;
	}

	public static SlfChildren getChildren() {
		setRequest();
		SlfUser slfUsre = getUser();
		SlfChildren children = (SlfChildren) RedisUtil.get(slfUsre.getPhone() + slfUsre.getUserId() + ChildrenService.REDIS_CHILDREN_CODE);
		if (null == children) {
			throw new IllegalArgumentException(ErrorUtil.CHILDREN_NULL);
		}
		return children;
	}
}
